import dayjs from "dayjs"
import {type App, ref} from "vue";

/** 格式化时间 */
export const formatDateTime = (time: string | number | Date) => {
    if (!time) {
        return "N/A"
    }
    const date = new Date(time)
    return dayjs(date).format("YYYY-MM-DD HH:mm:ss")
}

/** 将全局 CSS 变量导入 JS 中使用 */
export const getCssVariableValue = (cssVariableName: string) => {
    let cssVariableValue = ""
    try {
        // 没有拿到值时，会返回空串
        cssVariableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariableName)
    } catch (error) {
        console.error(error)
    }
    return cssVariableValue
}

export function showTimeSpace(space: number) {
    const d = dayjs.duration(space >= 0 ? space * 1000 : 0)
    return `${d.years() ? d.years() + '年' : ''}${d.months() ? d.months() + '月' : ''}${d.days() ? d.days() + '天' : ''}${d.hours() ? d.hours() + '小时' : ''}${d.minutes() ? d.minutes() + '分钟' : ''}${d.seconds() ? d.seconds() + '秒' : ''}` || "0秒"
}

/**
 * 给定字符串中出现的周几，并返回以逗号分隔的周几名称。
 * @param str
 */
export function weekShow(str: string) {
    if (!str) {
        return ""
    }
    const arr = str.split(',').map(e => +e).filter(e => [1, 2, 3, 4, 5, 6, 7].includes(e)).sort((a, b) => a - b)
    if (arr.length == 7) {
        return "全天"
    }
    const weekMap = {
        1: "周一",
        2: "周二",
        3: "周三",
        4: "周四",
        5: "周五",
        6: "周六",
        7: "周日"
    }
    let start = arr[0]
    let end = arr[0]
    const result = []
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] === end + 1) {
            end = arr[i];
        } else {
            if (start === end) {
                result.push(weekMap[start]);
            } else {
                result.push(`${ weekMap[start] }~${ weekMap[end] }`);
            }
            start = arr[i];
            end = arr[i];
        }
    }
    // 处理最后一组
    if (start === end) {
        result.push(weekMap[start]);
    } else {
        result.push(`${ weekMap[start] }~${ weekMap[end] }`);
    }
    return result.join('、');
}
/**
 * 全局挂载函数
 * @param app app
 */
export function extAppFun(app: App<Element>) {
}

